import { getInfo } from '@/api/login'
import cache from '@/plugins/cache'

const user = {
    state: {
        token: '',
        permissions: '',
        avatar: cache.session.getJSON('avatar'),
        roles: '',
        user: cache.session.getJSON('user')
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
            // cache.session.setJSON('token', token)
        },
        SET_PERMISSIONS: (state, permissions) => {
            state.permissions = permissions
            // cache.session.setJSON('permissions', permissions)
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
            cache.session.setJSON('avatar', avatar)
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
            // cache.session.setJSON('roles', roles)
        },
        SET_USER: (state, user) => {
            state.user = user
            cache.session.setJSON('user', user)
        }
    },

    actions: {
        // 登录
        Login({ commit }, token) {
            commit('SET_TOKEN', token)
        },

        // 获取用户信息
        GetInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                getInfo()
                    .then((res) => {
                        if (res.data.roles && res.data.roles.length > 0) {
                            // 验证返回的roles是否是一个非空数组
                            commit('SET_ROLES', res.data.roles)
                        } else {
                            commit('SET_ROLES', ['ROLE_DEFAULT'])
                        }
                        commit('SET_USER', res.data.user)
                        commit('SET_PERMISSIONS', res.data.permissions)
                        commit('SET_AVATAR', process.env.VUE_APP_BASE_API + res.data.user.avatar)
                        resolve(res)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        },

        // 退出系统
        LogOut({ commit, state }) {},

        // 前端 登出
        FedLogOut({ commit }) {}
    }
}

export default user
